package com.ningxun.pagent.bus.task;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.concurrent.TimeUnit;

@Component("wechatTokenTask")
public class WechatTokenTask {

    @Value("${wechat.appId:''}")
    private String appid;
    @Value("${wechat.secret:''}")
    private String secret;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    private static final String TOKEN_KEY = "WECHAT_TOKEN";
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(WechatTokenTask.class);

    public void refreshToken() {
        String url = UriComponentsBuilder.fromHttpUrl("https://api.weixin.qq.com/cgi-bin/token")
                .queryParam("appid", appid)
                .queryParam("secret", secret)
                .queryParam("grant_type", "client_credential")
                .toUriString();
        JSONObject res = restTemplate.getForObject(url, JSONObject.class);
        // 当token获取后
        if (res.containsKey("access_token")) {
            // 存入redis
            redisTemplate.opsForValue().set(TOKEN_KEY, res.get("access_token"),
                    res.getIntValue("expires_in"), TimeUnit.SECONDS);
        } else {
            //  记录日志
            logger.info("access_token获取失败.");
        }
    }
}
